package com.ryskoo.controller.promotion;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ryskoo.catering.coupon.domain.CouponPO;
import com.ryskoo.catering.coupon.service.ICouponService;
import com.ryskoo.catering.productmain.domain.ProductMainPO;
import com.ryskoo.catering.productmain.service.IProductMainService;
import com.ryskoo.common.constant.CouponConstant;
import com.ryskoo.common.hclconstant.CouponObtainTypeEnum;
import com.ryskoo.common.hclconstant.CouponTypeEnum;
import com.ryskoo.framework.core.bean.EnumConvertParam;
import com.ryskoo.framework.core.bean.Pager;
import com.ryskoo.framework.core.bean.QueryConditionEnum;
import com.ryskoo.framework.core.bean.QueryMessageDTO;
import com.ryskoo.framework.core.bean.ReturnCodeEnum;
import com.ryskoo.framework.core.bean.ReturnMessageDTO;
import com.ryskoo.framework.core.controller.BasicHandler;
import com.ryskoo.framework.core.utils.LoginUtil;

@Controller("caterCouponController")
@RequestMapping("/vendor/cater/coupon")
public class CouponController extends BasicHandler<CouponPO> {

    private static final String TEMPLATE_PATH = "system/promotion";

    private static final String MODULE_NAME = "Coupon";
    /**
     * 基类构造方法.
     */
    public CouponController() {
        super(TEMPLATE_PATH, MODULE_NAME);
    }

    private ICouponService couponService;

    @Autowired
    private IProductMainService productMainService;
    

    /**
     * 消费者注入
     *
     * @param productService 消费者基类
     */
    @Autowired
    protected void setService(ICouponService couponService) {
        this.couponService = couponService;
        super.setService(couponService);
    }
    
    @Override
	protected void buildListPageData(Model model, HttpServletRequest request) {
    	String vendorId = LoginUtil.getLoginVendorUuid();
		model.addAttribute("vendorId", vendorId);
		// 类型
		List<EnumConvertParam> couponTypeList = new ArrayList<>();
		for(CouponTypeEnum o : CouponTypeEnum.values()){
			EnumConvertParam param = new EnumConvertParam();
			param.setValue(o.getValue());
			param.setName(o.getName());
			couponTypeList.add(param);
		}
		model.addAttribute("couponTypeList", couponTypeList);
	}

	@Override
	protected void buildAddPageData(Model model, HttpServletRequest request) {
		String vendorId = LoginUtil.getLoginVendorUuid();
		model.addAttribute("vendorId", vendorId);
		// 类型
		List<EnumConvertParam> couponTypeList = new ArrayList<>();
		for(CouponTypeEnum o : CouponTypeEnum.values()){
			EnumConvertParam param = new EnumConvertParam();
			param.setValue(o.getValue());
			param.setName(o.getName());
			couponTypeList.add(param);
		}
		List<EnumConvertParam> obtainTypeList = new ArrayList<>();
		for(CouponConstant.ObtainTypeEnum o : CouponConstant.ObtainTypeEnum.values()){
			EnumConvertParam param = new EnumConvertParam();
			param.setValue(o.getValue());
			param.setName(o.getName());
			obtainTypeList.add(param);
		}
		// 发放方式
		model.addAttribute("obtainTypeList", obtainTypeList);
		model.addAttribute("couponTypeList", couponTypeList);
	}

	@Override
	protected void buildEditPageData(Model model, CouponPO po, HttpServletRequest request) {
		String vendorId = LoginUtil.getLoginVendorUuid();
		model.addAttribute("vendorId", vendorId);
	}


	/**
     * 优惠券启用/停用
     * @param id
     * @return
     */
    @PostMapping("/updateState")
    @ResponseBody
    public ReturnMessageDTO updateState(@RequestParam Boolean state,@RequestParam String uuid, HttpServletRequest request, HttpServletResponse response) {
    	ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            CouponPO coupon = couponService.getByUuid(uuid);
            if(coupon != null){
            	coupon.setState(state);
            	couponService.update(coupon);
            }
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
        }  catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
        }
        return returnMessage;
    }

    /**
     * 给会员发送优惠券时，查询优惠券列表
     * @param qm
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/listForSend")
    @ResponseBody
    public ReturnMessageDTO<List<CouponPO>> listForSend(@RequestBody QueryMessageDTO qm) {
        ReturnMessageDTO<List<CouponPO>> returnMessage = new ReturnMessageDTO<>();
        // 查询条件增加有效期范围
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = df.format(now);
        qm.addCondition("startValidTime",QueryConditionEnum.LE.name(),nowTime);
        qm.addCondition("endValidTime",QueryConditionEnum.GE.name(),nowTime);
        List<CouponPO> list = couponService.queryByCondition(qm);
        for (CouponPO po:list) {
            if(null!=po.getProductUuid()&&StringUtils.isNotEmpty(po.getProductUuid())){
                ProductMainPO product = productMainService.getByUuid(po.getProductUuid());
                po.setProductName(product.getName());
            }
        }
        returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
        returnMessage.setReturnNote("查询成功");
        returnMessage.setReturnMessage(list);
        return returnMessage;
    }

    /**
     * 给会员发送优惠券
     * @param memberUuids
     * @param couponUuids
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/sendCoupons")
    @ResponseBody
    public ReturnMessageDTO sendCoupons(@RequestParam(value = "memberUuids") String memberUuids,@RequestParam(value = "couponUuids") String couponUuids) {
        ReturnMessageDTO<List<CouponPO>> returnMessage = new ReturnMessageDTO<>();
        try {
            String[] memberUuidArr = memberUuids.split(",");
            String[] couponUuidArr = couponUuids.split(",");
            couponService.sendCouponsToMembers(memberUuidArr,couponUuidArr);
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("发送成功");
        }catch (Exception e){
            returnMessage.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
            returnMessage.setReturnNote(e.getMessage());
        }

        return returnMessage;
    }
    
    /**
     * 分页查询优惠券列表，带商品名称
     * @param qm
     * @return
     */
    @PostMapping("/listAndProductName")
    @ResponseBody
    public ReturnMessageDTO<List<CouponPO>> listAndProductName(@RequestBody QueryMessageDTO qm) {
        ReturnMessageDTO<List<CouponPO>> returnMessage = new ReturnMessageDTO<>();
        List<CouponPO> managerList = couponService.queryListAndProductByCondition(qm);
        int count = couponService.getCount(qm);
        returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
        returnMessage.setReturnNote("查询成功");
        returnMessage.setReturnMessage(managerList);
        returnMessage.setPager(new Pager(qm.getPageShow(), qm.getStartNum(), count));
        return returnMessage;
    }
    
    
    @Override
	public ReturnMessageDTO add(@RequestBody CouponPO po) {
    	// 如果是单品券，只能线下发放，且不限数量
    	if(CouponTypeEnum.PRODUCT.getValue() == po.getCouponType()){
	    	po.setObtainType(CouponObtainTypeEnum.OFFLINE.getValue());
	    	po.setLimitNum(0);
    	}
		return super.add(po);
	}

    
}
